import { map } from "lodash";
import React from "react";
import cx from "classnames";

import Button from "antd/lib/button";
import Upload from 'antd/lib/upload';
import message from 'antd/lib/message';
import { Row, Col } from 'antd/lib/grid';
import routeWithUserSession from "@/components/ApplicationArea/routeWithUserSession";
import Link from "@/components/Link";
import PageHeader from "@/components/PageHeader";
import Paginator from "@/components/Paginator";
import DynamicComponent from "@/components/DynamicComponent";
import { DashboardTagsControl } from "@/components/tags-control/TagsControl";
import { wrap as itemsList, ControllerType } from "@/components/items-list/ItemsList";
import { ResourceItemsSource } from "@/components/items-list/classes/ItemsSource";
import { UrlStateStorage } from "@/components/items-list/classes/StateStorage";
import * as Sidebar from "@/components/items-list/components/Sidebar";
import ItemsTable, { Columns } from "@/components/items-list/components/ItemsTable";
import useItemsListExtraActions from "@/components/items-list/hooks/useItemsListExtraActions";
import CreateDashboardDialog from "@/components/dashboards/CreateDashboardDialog";
import Layout from "@/components/layouts/ContentWithSidebar";

import { policy } from "@/services/policy";
import { Dashboard } from "@/services/dashboard";
import { currentUser } from "@/services/auth";
import routes from "@/services/routes";

import DashboardListEmptyState from "./components/DashboardListEmptyState";

import "./dashboard-list.css";

const sidebarMenu = [
  {
    key: "all",
    href: "dashboards",
    title: "所有报表",
  },
  {
    key: "favorites",
    href: "dashboards/favorites",
    title: "关注的报表",
    icon: () => <Sidebar.MenuIcon icon="fa fa-star" />,
  },
];

const listColumns = [
  Columns.favorites({ className: "p-r-0" }),
  Columns.custom.sortable(
    (text, item) => (
      <React.Fragment>
        <Link className="table-main-title" href={item.url} data-test={`DashboardId${item.id}`}>
          {item.name}
        </Link>
        <DashboardTagsControl
          className="d-block"
          tags={item.tags}
          isDraft={item.is_draft}
          isArchived={item.is_archived}
        />
      </React.Fragment>
    ),
    {
      title: "名称",
      field: "name",
      width: null,
    }
  ),
  Columns.custom((text, item) => item.user.name, { title: "创建人", width: "10%" }),
  Columns.dateTime.sortable({
    title: "创建时间",
    field: "created_at",
    width: "14%",
  }),
];

const uploadProps = {
  name: 'file',
  multiple: true,
  showUploadList: false,
  accept: `.${'json,.json'}`,
  action: `api/dashboards/import`,
  headers: {
    authorization: 'authorization-text',
  },
  onChange(info) {
    if (info.file.status !== 'uploading') {
      window.console.log(info.file, info.fileList);
    }
    if (info.file.status === 'done') {
      if (info.file.response.dashboardid > 0) {
        message.success(`${info.file.name}报表导入成功！建议对新报表的各部件数据源进行确认和刷新。${info.file.response.message}`);
        setTimeout(()=>{
          window.location.replace(`dashboards/${info.file.response.dashboardid}`);          
        }, 2000);
      } else {
        message.error(`${info.file.name} 报表导入失败！${info.file.response.message}`);
      }
    } else if (info.file.status === 'error') {
      message.error(`${info.file.name} 文件上载失败！${info.file.response.message}`);
    }
  },
};

function DashboardListExtraActions(props) {
  return <DynamicComponent name="DashboardList.Actions" {...props} />;
}

function DashboardList({ controller }) {
  const {
    areExtraActionsAvailable,
    listColumns: tableColumns,
    Component: ExtraActionsComponent,
    selectedItems,
  } = useItemsListExtraActions(controller, listColumns, DashboardListExtraActions);
  const imageUrl = policy.getHost() + '/static/images/templates/';

  return (
    <div className="page-dashboard-list">
      <div className="container">
        <PageHeader
          title={controller.params.pageTitle}
          actions={
            currentUser.hasPermission("create_dashboard") ? (
              <Button block type="primary" onClick={() => CreateDashboardDialog.showModal()}>
                <i className="fa fa-plus m-r-5" />
                新建报表
              </Button>
            ) : null
          }
        />
        <Layout>
          <Layout.Sidebar className="m-b-0">
            <React.Fragment>
              <Button block type="primary" href="dashboards/templates">
                <i className="fa fa-clone m-r-5" />
                从模板创建
              </Button>
              <br/><br/>
              <Button block type="primary" href="dashboards/export" style={{width: '190px'}}>
                <i className="fa fa-clone m-r-5" />
                批量导出报表
              </Button>&nbsp;&nbsp;&nbsp;&nbsp;
              <Upload {...uploadProps}>
                <button>
                  <i className="fa fa-archive m-r-5" />
                  导入报表
                </button>
              </Upload>
              <br/><br/>
            </React.Fragment>
            <Sidebar.SearchInput
              placeholder="搜索报表..."
              value={controller.searchTerm}
              onChange={controller.updateSearch}
            />
            <Sidebar.Menu items={sidebarMenu} selected={controller.params.currentPage} />
            <Sidebar.Tags url="api/dashboards/tags" onChange={controller.updateSelectedTags} showUnselectAll />
          </Layout.Sidebar>
          <Layout.Content>
            <div data-test="DashboardLayoutContent">
              {controller.isLoaded && controller.isEmpty ? (
                <DashboardListEmptyState
                  page={controller.params.currentPage}
                  searchTerm={controller.searchTerm}
                  selectedTags={controller.selectedTags}
                />
              ) : (
                <React.Fragment>
                  <div className={cx({ "m-b-10": areExtraActionsAvailable })}>
                    <ExtraActionsComponent selectedItems={selectedItems} />
                  </div>
                  <div className="bg-white tiled table-responsive">
                    {window.location.href.includes("/dashboards/templates") && (
                      <Row type="flex" gutter={[8, 8]} style={{width: '100%'}}>
                      {map(controller.pageItems, d=>(
                        <Col span={8} >
                          <button>
                            <Link href={`${d.template_url}`} target="_blank">
                              <img src={imageUrl + d.template_logo} alt={d.name} />
                            </Link>
                            <div>
                              <div style={{display:"inline",float:"left"}}>{d.name}</div>
                              <div style={{display:"inline",float:"right"}}>
                                {d.template_type !== 2 && (<Link href={`${d.template_url}`} target="_blank">&gt;&gt;查看</Link>)}
                                &nbsp;&nbsp;
                                <Link onClick={()=>CreateDashboardDialog.showModal({ id: d.id })}>&gt;&gt;创建</Link>
                              </div>
                            </div>
                          </button>
                        </Col>
                      ))}
                      </Row>
                    )}
                    {!window.location.href.includes("/dashboards/templates") && (
                    <ItemsTable
                      items={controller.pageItems}
                      loading={!controller.isLoaded}
                      columns={tableColumns}
                      orderByField={controller.orderByField}
                      orderByReverse={controller.orderByReverse}
                      toggleSorting={controller.toggleSorting}
                    />
                    )}
                    <Paginator
                      showPageSizeSelect
                      totalCount={controller.totalItemsCount}
                      pageSize={controller.itemsPerPage}
                      onPageSizeChange={itemsPerPage => controller.updatePagination({ itemsPerPage })}
                      page={controller.page}
                      onChange={page => controller.updatePagination({ page })}
                    />
                  </div>
                </React.Fragment>
              )}
            </div>
          </Layout.Content>
        </Layout>
      </div>
    </div>
  );
}

DashboardList.propTypes = {
  controller: ControllerType.isRequired,
};

const DashboardListPage = itemsList(
  DashboardList,
  () =>
    new ResourceItemsSource({
      getResource({ params: { currentPage } }) {
        return {
          all: Dashboard.query.bind(Dashboard),
          favorites: Dashboard.favorites.bind(Dashboard),
          templates: Dashboard.templates.bind(Dashboard),
        }[currentPage];
      },
      getItemProcessor() {
        return item => new Dashboard(item);
      },
    }),
  () => new UrlStateStorage({ orderByField: "created_at", orderByReverse: true })
);

routes.register(
  "Dashboards.List",
  routeWithUserSession({
    path: "/dashboards",
    title: "报表",
    render: pageProps => <DashboardListPage {...pageProps} currentPage="all" />,
  })
);
routes.register(
  "Dashboards.Favorites",
  routeWithUserSession({
    path: "/dashboards/favorites",
    title: "我关注的报表",
    render: pageProps => <DashboardListPage {...pageProps} currentPage="favorites" />,
  })
);
routes.register(
  "Dashboards.Templates",
  routeWithUserSession({
    path: "/dashboards/templates",
    title: "报表模板",
    render: pageProps => <DashboardListPage {...pageProps} currentPage="templates" />,
  })
);
routes.register(
  "Dashboards.Export",
  routeWithUserSession({
    path: "/dashboards/export",
    title: "导出报表",
    render: pageProps => <DashboardListPage {...pageProps} currentPage="all" />,
  })
);
